import path from 'path'
import config from '@/config'
import { connect } from 'net'
import { existsSync } from 'fs'
import { SendConnect } from './connect'
import { readIgnoreFile } from '@/utils/ignore'
import type { ParsedSendConfig, ParsedSendProjectConfig } from '@/types/configFile'

export class Send {
  constructor(
    config: ParsedSendConfig,
    currentConfig: ParsedSendProjectConfig,
    mode: SendMode = 'config'
  ) {
    this.config = config
    this.currentConfig = currentConfig
    this.mode = mode

    this.readIgnoreFile()

    this.connect = this.createConnect()
  }

  readonly config: ParsedSendConfig

  readonly currentConfig: ParsedSendProjectConfig

  readonly connect: SendConnect

  readonly startTime = new Date()

  readonly mode: SendMode

  private createConnect() {
    const socket = connect({
      host: this.currentConfig.host,
      port: this.currentConfig.port
    })
    return new SendConnect(socket, this)
  }

  private readIgnoreFile() {
    const ignoreFile = path.join(this.currentConfig.path, config.ignoreFile)
    if (existsSync(ignoreFile)) {
      const ignore = readIgnoreFile(ignoreFile)
      this.currentConfig.ignore.add(ignore)
    }
  }
}

export type SendMode = 'config' | 'param'
